import service from '@/utils/request'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const http = {
  post(url, params) {
    return service.post(url, params, {
      transformRequest: [(params) => {
        if (params) {
          let result = ''
          Object.keys(params).forEach((key) => {
            if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
              result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
            }
          })
          return result
        } else {
          return params
        }
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  postJson(url, params) {
    return service.post(url, params)
  },
  put(url, params) {
    return service.put(url, params)
  },
  get(url, params) {
    return service.get(url, { params })
  },
  delete(url, params) {
    return service.delete(url, { params })
  },
  download(url, params, filename) {
    NProgress.start()
    return service.get(url, { params }, {
      responseType: 'blob'
    }).then((response) => {
      const disposition = response.headers['content-disposition']
      const array = disposition.split(';')
      const obj = {}
      array.map(value => {
        const a = value.split('=')
        obj[a[0]] = a[1]
      })
      const content = response.data
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = filename || obj.filename
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, filename)
      }
      NProgress.done()
    }).catch((response) => {
      console.error(response)
      NProgress.done()
      Message({
        message: '下载失败',
        type: 'error'
      })
    })
  },
  upload(url, params) {
    return service.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}
export default http
